/**
 * Created by KaiBo on 2016/9/9.
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node / CommonJS
        factory(require('jquery'));
    } else {
        factory(jQuery);
    }
})(function ($) {
    var console = window.console || { log: function () {} };

    function CropAvatar($element){

        this.$container = $element;    //最外层div
        this.workspace = "/PY-Book/";

        this.$open = $(".open-cropper");  //打开裁剪
        this.$imgCover = this.$open.children(".img-cover");
        this.$imgCoverInput =  this.$open.children("[name='COVER']");

        this.$avatarWrapper = this.$container.find('.avatar-wrapper');     //编辑器外层div
        this.$avatar = this.$avatarWrapper.find('img');
        this.$avatarInput = this.$container.find('.avatar-input');    //本地文件按钮
        this.$avatarForm = this.$container.find('.avatar-form');
        this.$close = this.$container.find('.btn-close');
        this.$avatarSrc = this.$avatarForm.find('.avatar-src');     //隐藏数据
        this.$avatarData = this.$avatarForm.find('.avatar-data');    //隐藏数据

        this.$loading = $(".loading");
        this.init();
        //console.log(this);
    }

    CropAvatar.prototype = {
        constructor: CropAvatar,

        support: {
            fileList: !!$('<input type="file">').prop('files'),
            blobURLs: !!window.URL && URL.createObjectURL,
            formData: !!window.FormData
        },

        init:function(){
            this.addListener();
            this.initCropper();
        },
        initCropper:function(){
            var _this = this;
            _this.$avatar.cropper({
                aspectRatio: 1,
                crop: function (data) {
                    var json = [
                        '{"x":' + data.x,
                        '"y":' + data.y,
                        '"height":' + data.height,
                        '"width":' + data.width,
                        '"rotate":' + data.rotate + '}'
                    ].join();

                    _this.$avatarData.val(json);
                }
            });
        },
        addListener: function () {
            this.$avatarInput.on('change', $.proxy(this.change, this));
            this.$open.on("click",$.proxy(this.open, this));
            this.$close.on("click",$.proxy(this.close, this));
            this.$avatarForm.on('submit', $.proxy(this.submit, this));
            //this.$avatarForm.on('submit', $.proxy(this.submit, this));
        },
        open:function(){
            var _this = this;
            this.$container.show();
            $("#release").hide();
        },
        close:function(){
            this.$container.hide();
            $("#release").show();
        }
        ,
        isImageFile: function (file) {   //是否是图片
            if (file.type) {
                return /^image\/\w+$/.test(file.type);
            } else {
                return /\.(jpg|jpeg|png|gif)$/.test(file);
            }
        },
        submit: function () {
            if (!this.$avatarSrc.val() && !this.$avatarInput.val()) {
                alert("请选择文件数据");
                return false;
            }

            if (this.support.formData) {
                this.ajaxUpload();
                return false;
            }else{
                alert("系统正在维护当中...");
            }
        },
        ajaxUpload: function () {
            var url = this.$avatarForm.attr('action'),
                data = new FormData(this.$avatarForm[0]),
                _this = this;

            $.ajax(url, {
                type: 'post',
                data: data,
                dataType: 'json',
                processData: false,
                contentType: false,

                beforeSend: function () {
                    _this.submitStart();
                },

                success: function (data) {
                    _this.submitDone(data);
                },

                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    _this.submitFail(textStatus || errorThrown);
                },

                complete: function () {
                    _this.submitEnd();
                }
            });
        },
        submitStart: function () {
            //this.$loading.fadeIn();
        },

        submitDone: function (data) {
            //console.log(data);
            //$.isPlainObject(data)
            if (data.state == 1) {
                this.$imgCoverInput.val(data.data);
                this.$imgCover.attr("src",this.workspace+data.data);
                this.close();
            } else {
                alert('Failed to response');
            }
        },

        submitFail: function (msg) {
            alert(msg);
        },

        submitEnd: function () {
            //this.$loading.fadeOut();
        },
        change: function () {       //图片改变
            var files,
                file;

            files = this.$avatarInput.prop('files');
            if (files.length > 0) {
                file = files[0];

                if (this.isImageFile(file)) {
                    if (this.url) {
                        URL.revokeObjectURL(this.url);  // Revoke the old one
                    }

                    this.url = URL.createObjectURL(file);
                    this.startCropper();
                }
            } else {
                alert("抱歉，浏览器不支持啊，稍后完善！");
            }
        },
        startCropper: function () {
            var _this = this;

            if (this.active) {
                this.$img.cropper('replace', this.url);
            } else {
                this.$img = $('<img src="' + this.url + '">');
                this.$avatarWrapper.empty().html(this.$img);
                this.$img.cropper({
                    aspectRatio: 1,
                    crop: function (data) {
                        var json = [
                            '{"x":' + data.x,
                            '"y":' + data.y,
                            '"height":' + data.height,
                            '"width":' + data.width,
                            '"rotate":' + data.rotate + '}'
                        ].join();

                        _this.$avatarData.val(json);
                    }
                });

                this.active = true;
            }
        }
    };

    $(function () {
        return new CropAvatar($('#wrapper'));
    });
});